<template>
  <el-dialog :title="`${form.patSpotId ? '修改' : '添加'}巡更点`" :visible.sync="show" append-to-body :close-on-click-modal="false" :show-close="!btnLoading" width="800px" @closed="closed">
    <el-form ref="form" :model="form" :rules="rules" label-width="100px">
      <el-form-item prop="projectId" class="hide" />
      <el-form-item prop="patSpotId" class="hide" />
      <el-row :gutter="10">
        <el-col :span="12">
          <el-form-item label="巡更类型" prop="patrolTypeId">
            <treeselect v-model="form.patrolTypeId" :options="patTypeTree" :normalizer="patTypeNormalizer" disable-branch-nodes show-count placeholder="请选择巡更类型" :disabled="isEdit" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="点位标记" prop="positionType">
            <div class="d-flex">
              <el-button size="small" style="flex: 1" @click="openEditPosition">
                <el-link type="primary" style="font-size: 12px">{{ showPositionContent ? '点击重新定位' : '点击定位巡更点位置' }}</el-link>
              </el-button>
              <el-button size="small" style="padding: 10px" @click="clearPosition" v-if="showPositionContent">清除点位</el-button>
            </div>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10">
        <el-col :span="12">
          <el-form-item label="点位编码" prop="spotCode"><el-input v-model.trim="form.spotCode" placeholder="请输入点位编码" :maxlength="50" :disabled="isEdit" /></el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="点位名称" prop="spotName"><el-input v-model.trim="form.spotName" placeholder="请输入点位名称" :maxlength="100" /></el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="按楼层检查" prop="isFloor">
            <el-radio-group v-model="form.isFloor" @input="onChangeIsFloor">
              <el-radio v-for="dict in yesOrNo" :key="dict.value" :label="+dict.value">{{ dict.label }}</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="关联楼栋" prop="buildingId" :required="form.isFloor === 1">
            <el-select v-model="form.buildingId" placeholder="请选择楼栋" filterable clearable :loading="buildingLoading" style="width: 100%">
              <el-option v-for="item in buildingList" :key="item.fid" :label="item.fnameL2" :value="item.fid" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="点位负责人" prop="cqPatrolSpotBuilderList">
            <div class="custom-select" @click="openSelectUser">
              <el-select :value="principalNames" placeholder="请选择点位负责人" style="width: 100%" />
            </div>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="点位描述" prop="remark"><el-input v-model="form.remark" type="textarea" placeholder="请输入内容" :maxlength="255" /></el-form-item>
    </el-form>
    <div slot="footer">
      <el-button type="primary" :loading="btnLoading" @click="btnSubmit">确 定</el-button>
      <el-button :disabled="btnLoading" @click="show = false">取 消</el-button>
    </div>

    <EditBuilder ref="EditBuilder" @ok="onEditBuilder" />
    <EditPosition ref="EditPosition" v-model="showEditPosition" @ok="onEditPosition" />
  </el-dialog>
</template>
<script>
// 添加或修改巡更点
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import { flatList2tree, removeEmptyArray } from '@/utils'
import { nameRule } from '@/utils/validate'
import { editFormMixin } from '@/utils/mixin'
import { yesOrNo } from '@/utils/baseData'
import { listBuildingManage } from '@/api/baseManage/buildingManage'
import { listPatType, addSpot, setSpot } from '@/api/cq/patrol'
import EditBuilder from './EditSpotBuilder'
import EditPosition from './EditSpotPosition'
export default {
  components: { Treeselect, EditBuilder, EditPosition },
  mixins: [editFormMixin],
  data() {
    return {
      yesOrNo,
      primaryKey: 'patSpotId',
      addApi: addSpot,
      updateApi: setSpot,
      form: {
        projectId: '',
        patSpotId: '',
        patrolTypeId: null,
        spotCode: '',
        spotName: '',
        isFloor: 1,
        buildingId: '',
        cqPatrolSpotBuilderList: [],
        positionType: 0,
        positionObj: '',
        positionContent: '',
        positionFile: '',
        remark: ''
      },
      rules: {
        patrolTypeId: [{ required: true, message: '请选择巡更类型' }],
        // positionType: [{ required: true, message: '请选择巡更点位置' }],
        spotCode: [{ required: true, message: '请输入点位编码' }, nameRule],
        spotName: [{ required: true, message: '请输入点位名称' }, nameRule],
        isFloor: [{ required: true, message: '请选择是否按楼层检查' }],
        buildingId: [{ validator: (rule, val, cb) => cb(this.form.isFloor === 1 && !val ? '请选择关联楼栋' : undefined) }],
        cqPatrolSpotBuilderList: [{ required: true, message: '请选择点位负责人' }]
      },
      patTypeTree: [],
      buildingLoading: false,
      buildingList: [],
      showEditPosition: false
    }
  },
  computed: {
    isEdit() {
      return !!this.form.patSpotId
    },
    showPositionContent() {
      const { positionType, positionContent } = this.form
      // if (positionType === 0) return '无定位信息'
      if (positionType === 1) return positionContent
      return ''
    },
    principalNames() {
      const list = this.form.cqPatrolSpotBuilderList || []
      return list.map(i => i.userNickName).join(',')
    }
  },
  methods: {
    closed() {
      this.$refs.form.resetFields()
      this.buildingList = []
    },
    async opened(item = {}) {
      if (!this.patTypeTree.length) this.getPatTypeTree()
      this.getBuildingList()
    },
    patTypeNormalizer(node) {
      if (!node.children?.length) delete node.children
      return { id: node.patTypeId, label: node.patTypeName, children: node.children }
    },
    async getPatTypeTree() {
      this.patTypeLoading = true
      const res = await listPatType().catch(() => false)
      this.patTypeLoading = false
      if (res === false) return (this.patTypeTree = [])

      let data = res.data || []
      data = flatList2tree(data, { id: 'patTypeId' })
      data = removeEmptyArray(data)
      this.patTypeTree = data
    },
    async getBuildingList() {
      const { projectId } = this.form
      if (!projectId) return

      const opt = { cfcurprojectid: projectId }
      this.buildingLoading = true
      const res = await listBuildingManage(opt).catch(() => false)
      this.buildingLoading = false
      if (res === false) return
      this.buildingList = res.data || []
    },
    onChangeIsFloor() {
      this.$nextTick(() => this.$refs.form.clearValidate('buildingId'))
    },
    openSelectUser() {
      const { projectId } = this.form
      if (!projectId) return this.msgInfo('参数错误：项目ID不能为空')
      this.$refs.EditBuilder.open({
        projectId,
        patSpotId: this.form.patSpotId,
        list: this.form.cqPatrolSpotBuilderList || []
      })
    },
    onEditBuilder(data) {
      this.form.cqPatrolSpotBuilderList = data
      if (this.isEdit) this.$emit('ok')
    },
    openEditPosition() {
      const form = { ...this.form }
      form.positionType = 1
      this.$refs.EditPosition.open(form)
    },
    clearPosition() {
      const { form } = this
      form.positionType = 0
      form.positionObj = ''
      form.positionContent = ''
      form.positionFile = ''
    },
    onEditPosition(data) {
      this.form = { ...this.form, ...data }
    },
    async onSubmit() {
      const valid = await this.$refs.form.validate().catch(() => false)
      if (!valid) return

      const { isEdit } = this
      const opt = { ...this.form }
      if (isEdit) delete opt.cqPatrolSpotBuilderList

      this.btnLoading = true
      const submitApi = !isEdit ? addSpot : setSpot
      const res = await submitApi(opt).catch(() => false)
      this.btnLoading = false
      if (res === false) return

      this.msgSuccess(!isEdit ? '新增成功' : '提交成功')
      this.show = false
      this.$emit('ok')
    }
  }
}
</script>
<style lang="scss" scoped>
.custom-select {
  position: relative;
  cursor: pointer;
  &::before {
    content: '';
    position: absolute;
    width: 100%;
    height: 100%;
  }
  /deep/ {
    .el-select {
      pointer-events: none;
    }
    .el-input__suffix-inner {
      pointer-events: none;
    }
  }
}
</style>
